package com.zhkj.txg.module.order.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.find.adapter.FindPictureAdapter
import com.zhkj.txg.module.find.entity.FindPictureEntity
import com.zhkj.txg.module.order.popup.OrderReceiveReasonPopupWindow
import com.zhkj.txg.module.order.popup.OrderReceiveStatusPopupWindow
import com.zhkj.txg.module.order.vm.RefundViewModel
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.MatisseUtils
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.activity_order_refund_submit.*
import kotlinx.android.synthetic.main.item_order_goods.*

class OrderRefundSubmitActivity : ViewModelActivity<RefundViewModel>() {

    companion object {
        private val ORDER_ID = "orderId"
        private val GOODS_ID = "goodsId"
        private val TYPE = "type"
        private val ORDER_GROUP = "ORDER_GROUP"//拼团订单

        fun refund(activity: Activity, orderId: Long, goodsId: Long, isGroup: Boolean = false) {
            val intent = Intent(activity, OrderRefundSubmitActivity::class.java)
                .putExtra(ORDER_ID, orderId).putExtra(GOODS_ID, goodsId)
                .putExtra(TYPE, 0)
            if (isGroup) {
                intent.putExtra(ORDER_GROUP, isGroup)
            }
            activity.startActivity(intent)
        }

        fun reBack(activity: Activity, orderId: Long, goodsId: Long, isGroup: Boolean = false) {
            val intent = Intent(activity, OrderRefundSubmitActivity::class.java)
                .putExtra(ORDER_ID, orderId).putExtra(GOODS_ID, goodsId)
                .putExtra(TYPE, 1)
            if (isGroup) {
                intent.putExtra(ORDER_GROUP, isGroup)
            }
            activity.startActivity(intent)
        }
    }

    var isGroup: Boolean = false
    override fun setViewModel(): RefundViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleRefund
    override val layoutResId: Int = R.layout.activity_order_refund_submit

    private val requestCodePicture = 1010

    private val statusPopupWindow: OrderReceiveStatusPopupWindow by lazy {
        OrderReceiveStatusPopupWindow(this) { index, content ->
            viewModel.entity.goodsStatus = index
            tvRefundGoodsStatus.text = content
        }
    }
    private val reasonPopupWindow: OrderReceiveReasonPopupWindow by lazy {
        OrderReceiveReasonPopupWindow(this) {
            viewModel.entity.reason = it
            tvRefundReason.text = it
        }
    }
    private val pictureAdapter = FindPictureAdapter(6).apply {
        setOnItemClickListener { _, _, position ->
            // 添加按钮监听
            if (data[position].itemType == FindPictureEntity.TYPE_ADD) {
                requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE, {
                    selectPicture(6 - getRealPictureCount())
                }, { toast(getString(R.string.read_permission_deny)) })
            }
        }
        // 删除按钮监听
        setOnItemChildClickListener { _, _, position ->
            deletePicture(position)
        }
    }

    override fun initViewModel() {
        isGroup = intent.getBooleanExtra(ORDER_GROUP, false)
        viewModel.refundGoodsLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                ImageUtils.loadRoundCornerImage(this, ivOrderGoods, it.image)
                tvOrderGoodsName.text = it.goodsName
                tvOrderGoodsPrice.text = SpanUtil.setMoneySymbol(it.goodsPrice)
                tvOrderGoodsNumber.text = "x${it.goodsNumber}"
                tvRefundPrice.text = SpanUtil.setMoneySymbol(it.totalAmount)
            }
        })
        viewModel.refundSubmitLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip, true)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                toast(response.response?.msg ?: "")
                // 发送通知，页面刷新
                RxBus.post(OrderListRefreshEvent(listOf(Type.ALL, Type.COMPLETE)))
                val intent = Intent(this, OrderDetailActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                startActivity(intent)
            }
        })
    }

    override fun initData() {
        val orderId = intent.getLongExtra(ORDER_ID, 0)
        val goodsId = intent.getLongExtra(GOODS_ID, 0)
        val type = intent.getIntExtra(TYPE, 0)
        viewModel.entity.orderId = orderId
        viewModel.entity.goodsId = goodsId
        viewModel.entity.type = type
        // 获取数据
        viewModel.refundGoods(AccountManager.getToken(), isGroup)
        // 设置添加按钮
        pictureAdapter.addData(
            FindPictureEntity().apply {
                itemType = FindPictureEntity.TYPE_ADD
            })
        // 设置标题
        val content = getString(if (type == 0) R.string.order_refund else R.string.order_reBack)
        titleRefund.setTitleTextContent(content)
        viewRefundGoodsStatus.visibility = if (type == 0) View.VISIBLE else View.GONE
    }

    override fun initUI() {
        viewRefundGoodsStatus.setOnClickListener { statusPopupWindow.showPopupWindow() }
        viewRefundReason.setOnClickListener { reasonPopupWindow.showPopupWindow() }
        tvRefundSubmit.setOnClickListener {
            if (intent.getIntExtra(TYPE, 0) == 0 && tvRefundGoodsStatus.text.isNullOrEmpty()) {
                toast(getString(R.string.refund_goods_status_hint))
                return@setOnClickListener
            }
            if (tvRefundReason.text.isNullOrEmpty()) {
                toast(getString(R.string.refund_reason_hint))
                return@setOnClickListener
            }
            viewModel.entity.desc = etRefundOrder.text?.toString() ?: ""
            viewModel.refundSubmit(AccountManager.getToken(), pictureAdapter.data, isGroup)
        }
        with(rvRefundPicture) {
            layoutManager = GridLayoutManager(this@OrderRefundSubmitActivity, 3)
            adapter = pictureAdapter
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == requestCodePicture) {
            // 构造已选照片参数，填充Adapter
            val selectPicList = Matisse.obtainPathResult(data)
            if (selectPicList.isNotEmpty()) {
                val list = mutableListOf<FindPictureEntity>()
                for (filePath in selectPicList) list.add(FindPictureEntity(filePath).apply {
                    itemType = FindPictureEntity.TYPE_PIC
                })
                pictureAdapter.addPicture(list)
            }
        }
    }

    /**
     * 打开图片选择器
     */
    private fun selectPicture(selectNum: Int) {
        MatisseUtils.selectPicture(this, requestCodePicture, selectNum)
    }
}